<?php

/**
 * 司机贷款管理
 * @author  PVer
 * @date    2018-5-8 9:04:50
 * @version V1.0
 * @desc    
 */

namespace app\daikuan\controller;

use cmf\controller\AdminBaseController;
use app\daikuan\model\DriverInterestModel;
use app\portal\model\UserModel;
use app\daikuan\model\DriverLoanModel;
use app\daikuan\model\DriverModel;
use think\Db;

class DriverLoanController extends AdminBaseController {

    public function index() {
        $map = array();

        //        table排序
        $order = array();
        $order_type = input('order') ?? 'desc';
        $order_name = input('order_name') ?? 'a.Id';
        if (empty($order_name)) {
            $order_name = 'a.Id';
        }
        $order = "$order_name $order_type";

        $map['b.user_category'] = 1;
        $map['b.dk_status'] = 1;
        $status = input('status', -1, 'intval');
        if ($status >= 0){
            if($status ==0){
                $map['a.Status'] = array('in',array('0','5'));
            }else{
                $map['a.Status'] = $status;
            }

        }
        //即将逾期查询
        $yuqiday=Db::name('driver_interest')->where('id',1)->value('yujiday');

        $yuqi=input('yuqi',0);
        if($yuqi){
            $map['a.Status'] = 3;
//            $map['diffday'] = array('lt',$yuqiday);
        }

        $name = input('name');
        if (!empty($name)) {
            $map['b.user_nickname'] = array('like', "%$name%");
        }
        $list = db('driver_loan a')->join(array(array('dk_user b', 'a.DriverId=b.id ', 'LEFT')
                    , array('dk_user c', 'b.logistics=c.id', 'LEFT')
                ))
                ->field('a.*,b.user_nickname,b.mobile,b.create_time,b.number,c.user_nickname LogisticsName,DATEDIFF(now(),a.RepayMentDateTime)  diffday')
                ->where($map)
                ->order($order)
                ->paginate(10, false, ['query' => request()->param(),]);
         //echo db('driver_loan a')->getLastSql();
        $new_list=array();
        $driverInterestModel = new DriverInterestModel();
        $interes = $driverInterestModel->get(1);
        $yq = $interes['overdueInterest'];
        $overdueDay = $interes['overdueDay'];

        foreach ($list as $key=>$row) {
            $diffday = $row['diffday'];
            $lixi = 0;
            if ($diffday > 0) {
                $zq = ceil($diffday / $overdueDay);
                $lixi = $yq * $zq * $row['ApplyAmount'] / 100;
                //$lixi = $yq . '-' . $zq . '-' . $row['ApplyAmount'] . '-' . $lixi;
                $row['lixi'] = $lixi;
            } else {
                //$row['diffday'] = 0;
                $row['lixi'] = 0;
            }
            //即将逾期判断
            if($diffday<0) {
                if (abs($diffday) > $yuqiday) {
                } else {
                    if ($row['Status'] == 3) {
                        $row['yuday'] = abs($diffday);
                    }
                }
            }else{
                $row['yuday'] = 0;
            }

            if($yuqi){
                if($diffday<0){
                    if (abs($diffday) > $yuqiday) {
                        unset($row);
                    }else{

                    }
                }else{
                    unset($row);
                }
            }
            if($row) {
                $new_list[] = $row;
            }
        }
        //var_dump($new_list);exit;
        $page = $list->render();
        $this->assign('order', $order_type);
        $this->assign('Status', $status);
        $this->assign('list', $new_list);
        $this->assign('page', $page);
        $this->assign('yuqi', $yuqi);
        return $this->fetch();
    }

    public function myindex() {
        $map = array();
//        table排序
        $order = array();
        $order_type = input('order') ?? 'desc';
        $order_name = input('order_name') ?? 'a.Id';
        if (empty($order_name)) {
            $order_name = 'a.ApplyAmount';
        }
        $order = "$order_name $order_type";


        $map['b.user_category'] = 1;
        $map['b.dk_status'] = 1;
        $map["a.DriverId"] = cmf_get_current_admin_id();
        $status = input('status', -1, 'intval');
        if ($status >= 0) {
            $map['a.Status'] = $status;
        }

        $name = input('name');
        if (!empty($name)) {
            $map['user_nickname'] = array('like', "%$name%");
        }
        $list = db('driver_loan a')->join(array(array('dk_user b', 'a.DriverId=b.id ', 'LEFT')
                    , array('dk_user c', 'b.logistics=c.id', 'LEFT')
                ))
                ->field('a.*,b.user_nickname,b.mobile,b.create_time,b.number,c.user_nickname LogisticsName,DATEDIFF(now(),a.RepayMentDateTime)  diffday')
                ->where($map)
                ->order($order)
                ->paginate(10, false, ['query' => request()->param(),]);
        $page = $list->render();
        $this->assign('order', $order_type);
        $this->assign('Status', $status);
        $this->assign('list', $list);
        $this->assign('page', $page);
        return $this->fetch();
    }

    public function myadd() {
        $duserModel = new UserModel();
        $myinfo = $duserModel->where("id", cmf_get_current_admin_id())->find();
        $userModel = new UserModel();
        $loglist = $userModel->where("user_category=1")->select();
        $driverInterestModel = new DriverInterestModel();
        $interest = $driverInterestModel->find();
        $this->assign("myinfo", $myinfo);
        $this->assign("interest", $interest);
        $this->assign('log_list', $loglist);
        $this->assign('page', $page);
        return $this->fetch();
    }

    public function addloan() {
        $userModel = new UserModel();
        $loglist = $userModel->where("user_category=1")->select();
        $driverInterestModel = new DriverInterestModel();
        $interest = $driverInterestModel->find();
        $this->assign("interest", $interest);
        $this->assign('log_list', $loglist);
        $this->assign('page', $page);
        return $this->fetch();
    }

    public function addmyloanpost() {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $data["SeedAmount"] = $data["ReimAmount"];
            $driverLoanModel = new DriverLoanModel();
            $result = $driverLoanModel->save($data);
            if ($result !== false) {
                $this->success("操作成功", url("myindex"));
            } else {
                $this->error("操作失败");
            }
        }
    }

    public function addloanpost() {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $data["SeedAmount"] = $data["ReimAmount"];


            $log =Db::name('user')->where('id',$data['DriverId'])->find();
            $where['DriverId'] = $data['DriverId'];
            $where['Status'] = array('neq','4');
            $loan_money = Db::name('driver_loan')->where($where)->field('sum(ApplyAmount) as total_amount')->find();
            $loan_total_money = $loan_money['total_amount']+$data['ApplyAmount'];
            $syedu = $log['can_loan_amount'] - $loan_money['total_amount'];
            if($syedu<0){
                $syedu=0;
            }
            if($loan_total_money > $log['can_loan_amount']){
                $this->error("超过可以贷款的额度,还可以贷款".$syedu."元");
            }

            $driverLoanModel = new DriverLoanModel();
            $result = $driverLoanModel->save($data);
            if ($result !== false) {
                $this->success("操作成功", url("index"));
            } else {
                $this->error("操作失败");
            }
        }
    }

    public function see() {
        $id = input('id');
        $map = array();
        $map['a.Id'] = $id;
        $map['b.dk_status'] = 1;

        $info = db('driver_loan a')->join(array(array('dk_user b', 'a.DriverId=b.Id ', 'LEFT')
                    , array('dk_user c', 'b.logistics=c.id', 'LEFT')
                ))
                ->field('a.*,b.user_nickname,b.mobile,b.create_time,b.number,c.user_nickname LogisticsName,DATEDIFF(now(),a.RepayMentDateTime)  diffday')
                ->where($map)
                ->find();
        $diffday = 0;
        if (empty($info)) {
            $this->error("数据错误");
        } else {
            $diffday = $info['diffday'];
        }

        $lixi = 0;
        if ($diffday > 0) {
            $driverInterestModel = new DriverInterestModel();
            $interes = $driverInterestModel->get(1);
            $yq = $interes['overdueInterest'];
            $overdueDay = $interes['overdueDay'];
            $zq = ceil($diffday / $overdueDay);
            $lixi = $yq * $zq * $info['ApplyAmount'] / 100;
            // $lixi = $yq .'-'. $zq .'-'. $info['ApplyAmount'] .'-'.$lixi;
        } else {
            $info['diffday'] = 0;
        }
        $info['lixi'] = $lixi;

        $this->assign('info', $info);
        return $this->fetch();
    }

    public function edit() {
        $id = input('id');
        $map = array();
        $map['a.Id'] = $id;
        $map['b.dk_status'] = 1;
        $info = db('driver_loan a')->join(array(array('dk_user b', 'a.DriverId=b.Id ', 'LEFT')
                    , array('dk_user c', 'b.logistics=c.id', 'LEFT')
                ))
                ->field('a.*,b.user_nickname,b.mobile,b.create_time,b.number,c.user_nickname LogisticsName')
                ->where($map)
                ->find();
        if (empty($info)) {
            $this->error("数据错误");
        }

        $this->assign('info', $info);
        return $this->fetch();
    }

    public function fangkuan() {
        $driverInterestModel = new DriverInterestModel();
        $interest = $driverInterestModel->find();
        $this->assign("interest", $interest);

        $id = input('id');
        $map = array();
        $map['a.Id'] = $id;
        $map['b.dk_status'] = 1;
        $info = db('driver_loan a')->join(array(array('dk_user b', 'a.DriverId=b.Id ', 'LEFT')
                    , array('dk_user c', 'b.logistics=c.id', 'LEFT')
                ))
                ->field('a.*,b.user_nickname,b.mobile,b.create_time,b.number,c.user_nickname LogisticsName')
                ->where($map)
                ->find();

        if (empty($info)) {
            $this->error("数据错误");
        }
        $info['FangkuanDate'] = date('Y-m-d',time());
        $this->assign('info', $info);
        return $this->fetch();
    }

    public function editPost() {
        if ($this->request->isPost()) {
            $id = input('Id');
            $data = input('post.');
            $result = false;
            $loan = Db::name('DriverLoan')->where('Id',$id)->find();
            if($loan['Status'] !=5){
                $this->error("物流公司没有确认信息，无法审核");
            }
            if (isset($data['audit'])){ //通过审核
                //发送短信
                $loan = Db::name('DriverLoan')->where('Id',$id)->find();
                $user=Db::name('user')->where('id',$loan['DriverId'])->find();
                $nickname= $user['user_nickname'];
                $tpl_value = "#name#=$nickname&#code#=$id";
                $flag = sendcode($user['mobile'],'91658',$tpl_value);

                $arr = array();
                $arr["Status"] = 1;
                $result = model('DriverLoan')->save($arr, ['Id' => $id]);
            }elseif(isset($data['refuse'])){
                $arr = array();
                $arr["Status"] = 2;
                $arr['reason']=$data['reason'];
                $result = model('DriverLoan')->save($arr, ['Id' => $id]);
            }

            if ($result !== false) {
                $this->success("操作成功", url("index"));
            } else {
                $this->error("操作失败");
            }
        }
    }

    public function fangkuanPost() {
        if ($this->request->isPost()) {
            $id = input('Id');
            $data = input('post.');
            $result = false;
            if (isset($data['fangkuan'])) {
                $arr = array();
                $arr["Status"] = 3;
                $arr["FangkuanDate"] = $data['FangkuanDate'];
                $arr["RealDateLength"] = $data['RealDateLength'];
                $arr["RealAmount"] = $data['RealAmount'];
                $arr["serviceCharge"] = $data['serviceCharge'];
                $arr["RepayMentDateTime"] = $data['RepayMentDateTime2'];
                $arr["ReimAmount"] = $data['ReimAmount'];
                $arr["Interest"] = $data['Interest'];
                $arr["SeedAmount"] = $data['ReimAmount'];
                $result = model('DriverLoan')->save($arr, ['Id' => $id]);
            }
            if ($result !== false) {
                $this->success("操作成功", url("index"));
            } else {
                $this->error("操作失败");
            }
        }
    }

    public function getUserByName() {
        $data = input('post.');
        $map = array();
        $map['user_category'] = 1;
        $map['dk_status'] = 1;
        $name = input('UserName');
        if (!empty($name)) {
            $map['user_nickname'] = array('like', "%$name%");
        }
        $userModel = new UserModel();
        $result = $userModel
                ->where($map)
                ->select();
        //$result = model('Crop')->field('cropname')->select();
        $arr = array();
        foreach ($result as $row) {
            $arr[] = $row['user_nickname'];
        }

        return $result;
    }


    /**
     * 发送短信
     */
    public function sendmsg(){
        $data = input('post.');
        $id =input('Id');
        $yuday =input('yuday');
        $phone =input('phone');
        $nickname=input('nickname');
        $tpl_value = "#name#=$nickname&#code#=$id&#day#=$yuday";
        $flag = sendcode($phone,'91661',$tpl_value);
        if($flag){
            $this->success("发送成功", url("index"));
        }else{
            $this->error("发送失败");
        }

    }
}
